package com.wds.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wds.domain.entity.LoginUser;
import com.wds.domain.entity.User;
import com.wds.domain.type.SystemConstants;
import com.wds.mapper.UserMapper;
import com.wds.service.AdminAuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author WDs , wds8.24@outlook.com
 * @version 1.0
 * @since 2022-10-25 13:09
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdminAuthenticationService authenticationService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(queryWrapper);

        //
        if (Objects.isNull(user)){
            throw new RuntimeException("用户不存在");
        }
        //仅当时后台用户的时候封装权限信息
        if (SystemConstants.USER_TYPE_ADMIN.equals(user.getType())) {
            List<String> permissions = authenticationService.getPermissions(user.getId());
            return new LoginUser(user, permissions);
        }
        return new LoginUser(user,null);
    }


}
